﻿package {
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	
	public class Cannon extends Sprite {
	
		private var stepRotation:Number;
		private var targetRotation:Number;
		private var cannonSprite:CannonSprite;
		private var targetCoords;
		
		public function Cannon()
		{
			init();
		}
		
		private function init()
		{
			cannonSprite = new CannonSprite();
			cannonSprite.cannonBarrelSprite.gotoAndStop(0);
			
			addChild(cannonSprite);
		}
		
		public function aimAndFire(coords)
		{
			targetCoords = coords;
			targetRotation = getAngleTo(targetCoords);
			stepRotation = (targetRotation - cannonSprite.cannonBarrelSprite.rotation) / 10;
			
			addEventListener(Event.ENTER_FRAME, enterFrame);
		}
		
		public function fire()
		{
			cannonSprite.cannonBarrelSprite.gotoAndPlay(1);
		}
		
		private function enterFrame(event:Event)
		{
			if(Math.round(cannonSprite.cannonBarrelSprite.rotation) != Math.round(targetRotation))
			{
				cannonSprite.cannonBarrelSprite.rotation += stepRotation;
			}
			else
			{
				removeEventListener(Event.ENTER_FRAME, enterFrame);
				fire();
			}
		}
		
		private function getAngleTo(coords)
		{			
			var pt1:Point = new Point(cannonSprite.cannonBarrelSprite.x, cannonSprite.cannonBarrelSprite.y);
			pt1 = cannonSprite.cannonBarrelSprite.localToGlobal(pt1);
			
			var dx:Number = coords["x"] - pt1.x;
			var dy:Number = pt1.y - coords["y"]; 
			
			var angle = Math.atan2(dx, dy);
			var degrees = (angle * 180 / Math.PI);
			
			return degrees;
		}
		
		public function getTargetCoords():Object
		{
			return targetCoords;
		}
		
		public function getCannonLoudEndCoords():Object
		{
			var coords:Object = {"x": cannonSprite.cannonBarrelSprite.x + this.x, "y": cannonSprite.cannonBarrelSprite.y + this.y - cannonSprite.cannonBarrelSprite.height};

			return coords;
		}
	
	}
}